// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()

	console.log("addWrong-event: ", event)
	var myword = event.word_id
	var myopenid = wxContext.OPENID
	const countResult = await db.collection('wrongNote').where({
		word_id: myword,
		user_id: myopenid
	}).count()
	const num = countResult.total
	if (num == 0) {
		await db.collection('wrongNote').add({
			data: {
				word_id: myword,
				user_id: myopenid,
				number: 1,
			},
			success: function (res) {
				// res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
			}
		})
		return {
			msg: 'add'
		}
	} else { //若已经添加错题则增加做错的次数
		const result = await db.collection('wrongNote').where({
			word_id: myword,
			user_id: myopenid
		}).get();

		await db.collection('wrongNote').doc(result.data[0]._id).update({
			data: {
				number: db.command.inc(1),
			}
		});
		return {
			msg: 'update'
		}
	}
}